package com.qdlc.p2p.common.core.redis;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.data.redis.core.RedisTemplate;

import com.qdlc.p2p.common.util.BeanUtil;

/**
 * 获取JedisCache的工厂类
 * @author linya
 */
public class JedisCacheFactory implements BeanFactoryPostProcessor{
	
	private static final Map<Class<?>, JedisCache<?>> jedisCacheTypePool = new HashMap<Class<?>, JedisCache<?>>();
	
	private static BeanFactory beanFactory;
	
	private JedisCacheFactory(){}
	
	public static <T> JedisCache<T> newInstance(Class<T> valueClass){
		return newInstance(valueClass, beanFactory);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> JedisCache<T> newInstance(Class<T> valueClass, BeanFactory context){
		if(context == null){
			context = BeanUtil.getApplicationContext();
		}
		
		JedisCache<T> handler = null;
		if(jedisCacheTypePool.containsKey(valueClass)){
			handler = (JedisCache<T>) jedisCacheTypePool.get(valueClass);
		}else{
			//获取Redis模版，这是一个单例对象
			RedisTemplate<String, T> redisTemplate = context.getBean(RedisTemplate.class);
			handler = new JedisCache<T>(redisTemplate, valueClass);
			jedisCacheTypePool.put(valueClass, handler);
		}
		
		return handler;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		JedisCacheFactory.beanFactory = beanFactory;
	}
	
}
